from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse

from utils.jwttool import tooljwt
from utils.myredis import redistoll

import time, json


class PermitionMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 定义一个白名单
        wlist = ["/mobilecode/", "/register/", "/login/"]
        url = request.path

        if url not in wlist:
            # 从头部获取token，验证token是否被修改，是否过期，是否退出，是否有权限操作
            try:
                token = request.headers.get('Authorization')
                data = tooljwt.jwt_decode(token)
                now = int(time.time())
                if now > data['exp']:
                    return JsonResponse({"code": 401, "message": "token过期"})
                # 验证用户是否已经退出
                value = redistoll.get_str(token)
                if value:
                    return JsonResponse({"code": 401, "message": "用户已经退出，非法操作"})
            except:
                return JsonResponse({"code": 401, "message": "操作异常"})
